/**
 * @description 数据请求的公用方法
 * @author captern
 */
import axios from "./http"
import storage from "good-storage"
import { observer, inject } from "mobx-react"
import { getQuery, removeQuery } from "../utils/common"
import Qs from "qs"
import userAuthFun from "./userAuth"
import store from "../stores"

@inject("UserStore")
@observer
class HttpRequest {
  static request(url, data, method) {
    return new Promise((resolve, reject) => {
      this._requestFun(url, data, method, resolve, reject)
    })
  }

  static _requestFun(url, data = {}, method = "GET", resolve, reject) {
    let requestData = {
      url: url,
      data: data,
      method: method,
    }

    if (method === "POST") {
      axios
        .post(url, data)
        .then((res) => {
          this.checkCode(res, requestData, resolve, reject)
        })
        .catch((res) => {
          resolve(res)
        })
    } else if (method === "GET") {
      axios
        .get(url, {
          headers: {
            // Authorization: 'token ' + this.props.UserStore.token,
          },
        })
        .then((res) => {
          this.checkCode(res, requestData, resolve, reject)
        })
        .catch((res) => {
          resolve(res)
        })
    }
  }

  static checkCode(res, requestData, resolve, reject) {
    let codeChecked = res.data.code
    if (codeChecked == 5003 || codeChecked == 5005 || codeChecked == 5000) {
      store.UserStore.setNeedUpdateAuth(true)
      this._refetch(requestData, resolve, reject)
      // resolve('asddsadsdaddaadsadads')
    } else if (codeChecked === 0 || codeChecked === 200) {
      resolve(res.data)
    } else {
      resolve(res.data)
    }
  }

  static _refetch(requestData, resolve, reject) {
    storage.remove("access_token")
    storage.remove("uid")
    let _this = this
    // window.location.href = asd
    if (getQuery("code")) {
      removeQuery("code", window.location.href)
    }
    userAuthFun.checkUserAuth((userAuthFlag, type = "reset") => {
      // 重置token数据
      if (userAuthFlag && type && type == "reset") {
        let url = requestData.url
        let data = requestData.data
        let method = requestData.method
        _this._requestFun(url, data, method, resolve, reject, true) // 获取新token之后要重新请求之前失败的接口
      }
    })
  }
}

export default HttpRequest
